package yang.java8.OptionalApi;

import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Stream;

import yang.java8.util.MyObject;
import yang.java8.util.Util;

@SuppressWarnings("unused")
public class OptionalStudy {

	public static void main(String[] args) {
		useOptional();
	}
	
	public static void useOptional() {
		Stream<MyObject> stream = Util.generateMyObjectList(100).stream();
		Optional<MyObject> optional = stream.findFirst();
		
		optional.ifPresent(v -> System.out.println(v));
		optional.ifPresent(System.out::println);
		Optional<Boolean> added = optional.map(v -> v.toString() == "");
		
		// 若封装的为null则返回默认值
		MyObject myObject = optional.orElse(new MyObject(0, ""));
		// 调用代码来计算默认值， 函数只有在必要的时候才会调用，不像之前创建损耗
		MyObject re = optional.orElseGet(() -> (MyObject) null);
		// 没有值的时候抛出一个异常
		re = optional.orElseThrow(NoSuchElementException::new);
	}
	
	public static void createOptional() {
		Double x = 0.0;
		// 创建空的或者有值的optional对象
		Optional<Double> ret = x == 0 ? Optional.empty() : Optional.of(x);
		// null则返回empty，否则返回有值对象
		ret = Optional.ofNullable(x);
	}
	
	public static void flatMap() {
		Double x = 0.0;
		
		Optional<Double> result = inverse(x).flatMap(OptionalStudy::squareRoot);
		result = Optional.of(-4.0).flatMap(OptionalStudy::squareRoot).flatMap(OptionalStudy::squareRoot);
	}
	
	public static Optional<Double> squareRoot(Double x) {
		// 小于0，返回空。否则返回值 平方根
		return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
	}
	
	public static Optional<Double> inverse(Double x) {
		// 小于0，返回空。否则返回值 翻转
		return x == 0 ? Optional.empty() : Optional.of(1 / x); 
	}

}
